<?php

/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/9/28
 * Time: 17:15
 */

namespace app\common\model;


use think\Model;
use think\db\Query;

class Equipment extends Model
{


    public $page_info;

    public function getEquipmentList($condition, $page = '', $order = 'ne.created_at desc')
    {
        if ($page) {
            $result = db('new_equipment')->alias('ne')
                ->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')
                ->join('fuwu_personal fp', 'fp.id = ne.member_id')
                ->where($condition)
                ->field('ne.*,neb.*,fp.name,fp.id as fuwu_id')
                ->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $result;
            return $result->items();
        } else {
            return db('question')->where($condition)->order($order)->limit(10)->select();
        }
    }

    //测试设备库
    public function getNquipmentList($condition, $page = '', $order = 'created_at desc')
    {
        if ($page) {
            $result = db('new_equipment')->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $result;
            return $result->items();
        } else {
            return db('question')->where($condition)->order($order)->limit(10)->select();
        }
    }

    //测试设备库-- 品牌
    public function getNquipmentBrandList($condition, $page = '', $order = 'equipment_brand_id asc')
    {
        if ($page) {
            $result = db('new_equipment_brand')->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
            $this->page_info = $result;
            return $result->items();
        } else {
            return db('question')->where($condition)->order($order)->limit(10)->select();
        }
    }

    //两表联查
    public function getNquipmentBrandsList($condition, $page = '', $order = 'id asc')
    {
        if ($page) {
            $post_data = request()->param();
            /*  $result = db('new_equipment')->alias('ne')->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')
                ->where($condition)->order($order)->paginate($page, false, ['query' => request()->param()]);
            p($result);die;
            $this->page_info = $result;
            return $result->items();*/

            $deveice_list = db('new_equipment')->alias('ne')->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')
                ->where($condition)->order($order)->select();

            #循环了多少次，键值就是几，  二维数组是以小数组来决定的    //判断是几位数组
            $new = [];
            foreach ($deveice_list as $key => $value) {
                $speci_type = [];
                if (!empty($value['spec_value_type'])) {
                    $speci_type = unserialize($value['spec_value_type']); # 获取规格型号
                    foreach ($speci_type as $k => $v) {
                        $new[] = [
                            'id' => $value['id'],
                            'specifications' => $v,
                            'class_name' => $value['class_name'],
                            'equipment_brand_id' => $value['equipment_brand_id'],
                            'goods_name' => $value['goods_name'] . ' ' . $v,
                            'brand_name' => $value['brand_name'],
                            'is_question' => 0,
                            'question_id' => $value['question_id'],
                        ];
                        if ($value['question_id'] > 0) {
                            $new[count($new) - 1]['is_question'] = 1;
                        }
                    }
                } else {
                    $new[] = [
                        'id' => $value['id'],
                        'equipment_brand_id' => $value['equipment_brand_id'],
                        'goods_name' => $value['goods_name'],
                        'class_name' => $value['class_name'],
                        'brand_name' => $value['brand_name'],
                        'specifications' => '',
                        'is_question' => 0,
                        'question_id' => $value['question_id'],
                    ];
                    if ($value['question_id'] > 0) {
                        $new[count($new) - 1]['is_question'] = 1;
                    }
                }
            }
            $query = new Query();


            if (isset($post_data['page'])) {
                $new_data = $this->page_array($page, $post_data['page'], $new);
            } else {
                $new_data = $this->page_array($page, 1, $new);
            }
            $result = $query->array_paginate($page, false, ['query' => request()->param()], count($new), $new_data);
            $this->page_info = $result;
            return $result->items();
        } else {
            return db('question')->where($condition)->order($order)->limit(10)->select();
        }
    }

    /**
     * Notes: 数组分页
     * User: shen
     * Date: 2020/5/17
     * Time: 16:34
     * @param $count
     * @param $page
     * @param $array
     * @param $order
     * @return array
     */
    public function page_array($count, $page, $array)
    {
        global $countpage; #定全局变量
        $page = (empty($page)) ? '1' : $page; #判断当前页面是否为空 如果为空就表示为第一页面
        $start = ($page - 1) * $count; #计算每次分页的开始位置
        $totals = count($array);
        $countpage = ceil($totals / $count); #计算总页面数
        $pagedata = array();
        $pagedata = array_slice($array, $start, $count);
        return $pagedata;  #返回查询数据
    }

    public function object_array($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

    //对象转数组
    public function array_object($object)
    {
        $object = (array)$object;
        foreach ($object as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $object[$k] = (array)$this->array_object($v);
            }
        }

        return $object;
    }


    /**
     * 取单条订单信息
     * @access public
     * @param array $condition 条件
     * @param array $extend 扩展
     * @param string $fields 字段
     * @param array $order 排序
     * @param array $group 分组
     * @return array
     * @author csdeshang
     */
    public function getEquipmentInfo($condition = array(), $extend = array(), $fields = '*', $order = '', $group = '')
    {

        $order_info = db('s_order')->field($fields)->where($condition)->group($group)->order($order)->find();

        if (empty($order_info)) {
            return array();
        }

        return $order_info;
    }

    public function getEquipmentInfoByKeyword($keyword)
    {
        $info = db('equipment')
            ->field('id, goods_name, specifications, type_model, question_id, class_name, gc_one_id, gc_two_id, gc_three_id')
            ->where('equipment_del', 0)
            ->where('goods_name', 'like', "%$keyword%")
            ->find();
        if ($info) {
            $class = explode('>', $info['class_name']);
            $info['categroy'] = array(
                array(
                    'id' => $info['gc_one_id'],
                    'title' => isset($class[0]) ? $class[0] : ''
                ),
                array(
                    'id' => $info['gc_two_id'],
                    'title' => isset($class[1]) ? $class[1] : ''
                ),
                array(
                    'id' => $info['gc_three_id'],
                    'title' => isset($class[2]) ? $class[2] : ''
                ),
            );
            $info['question'] = [];
            unset($info['class_name']);
            unset($info['gc_one_id']);
            unset($info['gc_two_id']);
            unset($info['gc_three_id']);
        }

        return $info;
    }

    public function getEquipmentInfoById($ids, $type)
    {
        $goodsInfo = [];
        foreach ($ids as $id) {
            // $info = db('equipment')
            //     ->field('id, goods_name, b_name, type_model, question_id')
            //     ->find($id);
            $info = db('new_equipment')->alias('ne')
                ->join('new_equipment_brand neb', 'neb.equipment_id=ne.id')
                ->where(['id' => $id])
                ->select();

            //请求类型 0-维修 1-安装 2-保养 3-迁移机
            switch ($type) {
                case 0:
                    $info['optionList'] = db('equipment_option')
                        ->field('id oid,content')
                        ->where('equipment_id', $id)
                        ->select();
                    break;
                case 1:
                    $info['optionList'] = [];
                    break;
                case 2:
                    $info['optionList'] = db('equipment_option')
                        ->field('id oid,content')
                        ->where('equipment_id', $id)
                        ->select();
                    break;
                case 3:
                    $info['optionList'] = array(
                        array(
                            'oid' => 1,
                            'title' => '拆机'
                        ),
                        array(
                            'oid' => 2,
                            'title' => '安装'
                        )
                    );
                    break;
            }

            $goodsInfo[] = $info;
        }

        $scienceInfo = db('equipment_science')
            ->field('id sid, science')
            ->where('equipment_id', 'in', $ids)
            ->order('sort')
            ->select();

        $data = ['goods_list' => $goodsInfo, 'scienceList' => $scienceInfo];

        return $data;
    }

    public function addQuestion($data)
    {
        $result = $this->insertGetId($data);
        return $result;
    }

    public function getOneQuestion($condition)
    {
        $result = db('question')->where($condition)->find();
        return $result;
    }

    /**
     * 增加子类问题方法
     * @param $data
     * @param $parent_id
     *
     * @return bool
     */
    public static function addChildQuestion($data, $parent_id)
    {
        // 增加子类问题
        $model = new Question();
        $model->title = $data['title'];
        $model->gc_id1 = $data['gc_id1'];
        $model->gc_id2 = $data['gc_id2'];
        $model->gc_id3 = $data['gc_id3'];
        $model->parent_id = $parent_id;
        $model->created_at = date('Y-m-d H:i:s');
        $model->updated_at = date('Y-m-d H:i:s');
        if (!$model->save()) {
            return false;
        }
        // 处理父级问题中的下级问题id
        if (!self::_parentNextIdAdd($parent_id, $model->id)) {
            return false;
        }

        return true;
    }

    /**
     * 修改父类问题中的下级问题id字段
     * @param $parent_id
     * @param $model_id
     *
     * @return bool
     * @throws \think\exception\DbException
     */
    protected static function _parentNextIdAdd($parent_id, $model_id)
    {
        $model = self::get($parent_id);
        if (empty($model)) {
            return false;
        }
        if ($model->next_id == 0) {
            $model->next_id = '';
        }
        // 将问题信息中的下级id全部取出来
        $next_id = explode(',', $model->next_id);
        array_push($next_id, $model_id);
        $next_id = implode(',', $next_id);
        $model->next_id = trim($next_id, ',');
        $model->updated_at = date('Y-m-d H:i:s');
        if ($model->save()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 传入父级问题id返回所有父级问题对象
     * @param $parent_id
     */
    public static function getAllParentQuestions($parent_id)
    {
        if (is_string($parent_id)) {
            $parent_id = explode(',', $parent_id);
        }
        $parents = self::where('id', 'in', $parent_id)->select();

        return $parents;
    }

    public static function deleteParentId($id, $parent_id)
    {
        $model = self::find($id);
        if (empty($model)) return false;
        $parent_ids = explode(',', $model->parent_id);
        foreach ($parent_ids as $key => $val) {
            if ($val == $parent_id) {
                unset($parent_ids[$key]);
            }
        }
        $parent_ids = trim(implode(',', $parent_ids), ',');
        if (empty($parent_ids)) $parent_ids = 0;
        $model->parent_id = $parent_ids;
        $model->updated_at = date('Y-m-d H:i:s');
        if (!$model->save() || !self::deleteNextId($parent_id, $id)) {
            return false;
        }
        return true;
    }

    public static function deleteNextId($id, $next_id)
    {
        $model = self::find($id);
        if (empty($model)) return false;
        $next_ids = explode(',', $model->next_id);
        foreach ($next_ids as $key => $val) {
            if ($val == $next_id) {
                unset($next_ids[$key]);
            }
        }
        $next_ids = trim(implode(',', $next_ids), ',');
        if (empty($next_ids)) $next_ids = 0;
        $model->next_id = $next_ids;
        if (!$model->save()) {
            return false;
        }

        return true;
    }

    /**
     * 判断是否存在子类问题
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function hasNextQuestions($id)
    {
        $model = self::find($id);
        if ($model->next_id != 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 关联答案id
     * @param $id
     * @param $answer_id
     *
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function addAnswer($id, $answer_id)
    {
        $question = self::find($id);
        if (!$question) return false;
        if ($question->answer_id == 0) $question->answer_id = '';
        $answer_ids = explode(',', $question->answer_id);
        foreach ($answer_ids as $k => $v) {
            if (empty($v)) unset($answer_ids[$k]);
        }
        array_push($answer_ids, $answer_id);
        $answer_ids = trim(implode(',', $answer_ids), ',');
        $question->answer_id = $answer_ids;
        if ($question->save()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取指定位置下的答案列表
     * @param $id
     *
     * @return bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAnswer($id)
    {
        $question = self::find($id);
        if (!$question) return false;
        return Answer::getAnswerById($question->answer_id);
    }

    public static function getAnswerList($id)
    {
        $question = self::find($id);
        if (!$question) return false;
        return Answer::getAnswerByNotInId($question->answer_id);
    }

    public static function deleteAnswer($id, $answer_id)
    {
        $question = self::find($id);

        if (!$question) return false;

        $answer = explode(',', $question->answer_id);

        foreach ($answer as $key => $val) {
            if ($val == $answer_id) {
                unset($answer[$key]);
            }
        }

        $answer = trim(implode(',', $answer), ',');
        if (empty($answer)) $answer = 0;
        $question->answer_id = $answer;
        if ($question->save()) {
            return true;
        } else {
            return false;
        }
    }

    public static function getCategoryName($id)
    {
        $class = new Goodsclass();
        $cate = $class->find(['gc_id' => $id]);
        if ($cate) {
            return $cate->gc_name;
        }
        return '';
    }

    /**
     * 服务单  追加订单
     * @param array $order_info
     * @return array
     */
    public function getAppendSorder($data, $service_id, $memberId, $member_name)
    {
        #获取主单的详细信息
        $order_info = db('s_order')->where(['order_id' => $service_id])->find();

        //获取预约地址详细信息
        $address_info = db('address')->where(['address_id' => $order_info['address_id']])->find();

        // 1.下服务单
        $orderData = array(
            'order_sn' => $order_info['order_sn'],
            'order_type' => $data['order_type'],
            'service_type' => 1,
            'parent_id' => $service_id,
            'member_id' => $memberId,
            'member_name' => $member_name,
            'assign_mechanic_id' => $order_info['assign_mechanic_id'],
            'assign_mechanic_name' => $order_info['assign_mechanic_name'],
            'appointment_time' => $order_info['appointment_time'],
            'add_time' => time(),
            'update_time' => time(),
            'remarks' => $order_info['remarks'],
            'address_id' => $order_info['address_id'],
            'appoint_phone' => $address_info['address_tel_phone'],
            'appoint_address' => $address_info['area_info'],
            'appoint_detail_address' => $address_info['address_detail'],
            'appoint_city' => $address_info['city_id'],
            'is_backstage' => 1,
            'appoint_district' => $address_info['area_id'],
        );
        $orderId = db('s_order')->insertGetId($orderData);

        //2.服务单详情单
        $goodsItems = json_decode(htmlspecialchars_decode($data['goods_items']), true);
        // if(count($goodsItems) > 1){
        //     return json_fail_return('一次追加一个设备！');
        // }
        foreach ($goodsItems as $goodsItem) {
            $detailInfo = array(
                'order_id' => $orderId,
                'goods_id' => $goodsItem['id'],
                'goods_name' => $goodsItem['goods_name'],
                'b_name' => $goodsItem['b_name'],
                'type_model' => $goodsItem['type_model'],
                'add_time' => time(),
                'scienceIds' => $goodsItem['scienceIds'],
                'diagnostic_cause' => $goodsItem['diagnostic_cause']
            );
            //如果是维修单，并且传了诊断结果
            if ($data['order_type'] == 2 && isset($goodsItem['diagnostic_results'])) {
                $detailInfo['diagnostic_results'] = $goodsItem['diagnostic_results'];
            }
            //如果是维修单保养单可以选择部位，移机单选择拆机和安装这部分统一按照部位存储json串进optionCheckInfo
            if (in_array($data['order_type'], [2, 3, 4]) && isset($goodsItem['optionList']) && $goodsItem['optionList']) {
                $detailInfo['option_info'] = json_encode($goodsItem['optionList']);
            }

            #判断是手动添加还是选择设备
            if ($goodsItem['id'] == 0) {
                $detailInfo['place_type'] = 0; #录入设备
                #手动添加
                //处理分类
                $class = db('goodsclass')->where(['gc_id' => $goodsItem['goods_class']])->find();
                if (empty($class['gc_parent_id'])) {
                    //没父值的话就是一级分类id
                    $detailInfo['gc_one_id'] = $class['gc_id'];
                    $detailInfo['gc_id'] = $class['gc_id'];
                    $detailInfo['class_name'] = $class['gc_name'];
                } else {
                    //有父值的话再往上找
                    $class_one = db('goodsclass')->where(['gc_id' => $class['gc_parent_id']])->find();
                    if (empty($class_one['gc_parent_id'])) {
                        $detailInfo['gc_one_id'] = $class_one['gc_id'];
                        $detailInfo['gc_two_id'] = $class['gc_id'];
                        $detailInfo['gc_id'] = $class['gc_id'];
                        $detailInfo['class_name'] = $class_one['gc_name'] . '>' . $class['gc_name'];
                    } else {
                        $class_two = db('goodsclass')->where(['gc_id' => $class_one['gc_parent_id']])->find();
                        $detailInfo['gc_one_id'] = $class_two['gc_id'];
                        $detailInfo['gc_two_id'] = $class_one['gc_id'];
                        $detailInfo['gc_three_id'] = $class['gc_id'];
                        $detailInfo['gc_id'] = $class['gc_id'];
                        $detailInfo['class_name'] = $class_two['gc_name'] . '>' . $class_one['gc_name'] . '>' . $class['gc_name'];
                    }
                }
            }

            #拆移机类型
            if ($data['order_type'] == 3) {
                $detailInfo['disma_status'] = $goodsItem['disma_status'];
            }

            $detailId = db('s_order_detail')->insertGetId($detailInfo);
            if (!$detailId) {
                return json_fail_return('服务单辅助单生成失败！');
            }

            //3.服务单图片记录存储
            if (isset($goodsItem['science_pics']) && $goodsItem['science_pics']) {
                $pic = array(
                    'order_detail_id' => $detailId,
                    'src' => $goodsItem['science_pics']
                );
                $status = db('s_order_image')->insert($pic);
                if (!$status) {
                    return json_fail_return('服务单图片地址保存失败！');
                }
            }
        }
        #服务单订单日志
        $data = array();
        $data['order_id'] = $service_id;
        $data['log_msg'] = '客户追加设备订单';
        $data['log_time'] = time();
        $data['log_role'] = 'buyer';
        $data['log_user'] = $memberId;
        $data['log_orderstate'] = 1;

        model('order')->addSorderlog($data);
        return $orderId;
    }

    /**
     * 服务单更换服务人员
     * @param array $order_info
     * @return array
     */
    public function ChangePersonnel($data, $member_id)
    {

        //获取当前服务单详情  多条
        $order_info = db('s_order')->alias('s')->join('s_order_detail sg', 'sg.order_id=s.order_id')->where(['s.order_id' => $data['order_id'], 's.service_type' => 0])->select();

        if (empty($order_info)) {
            return json_fail_return('暂无可操作订单');
        }

        //修改主单状态，先改为疑问单，等客服审核过之后再改为待派单
        db('s_order')->where(['order_id' => $data['order_id'], 'member_id' => $member_id])->update(['order_state' => 7, 'is_mechanic_change' => 1]);

        //找到订单分派表，将当前状态改为拒单
        // db('s_order_mechanic')->where(['order_id' => $data['order_id']])->update(['status' => 2]);

        //生成一条记录，由后台审核，审核通过之后，再次由客服派单，一对多，（订单分派表）,还得修改主单状态
        $change_data = [
            'order_id' => $data['order_id'],
            'member_id' => $member_id, #操作人
            'mechanic_id' => $data['mechanic_id'], #当前服务人员的id
            'refusal_reason' => $data['refusal_reason'],
            'refusal_remake' => $data['refusal_remake'],
            'c_time' => time(),
            'status' => 0, #0待审核 1审核通过 2审核失败
        ];

        db('s_order_change')->insertGetId($change_data);

        #服务单订单日志
        $s_data = array();
        $s_data['order_id'] = $data['order_id'];
        $s_data['log_msg'] = '更换服务人员';
        $s_data['log_time'] = time();
        $s_data['log_role'] = 'buyer';
        $s_data['log_user'] = $member_id;
        $s_data['log_orderstate'] = 1;

        model('order')->addSorderlog($s_data);
        return [];
    }

    /**
     * 服务单  服务完成
     * @param array $order_info
     * @return array
     */
    public function SorderCompletion($order_id, $member_id)
    {
        //获取当前服务单详情  多条
        $order_info = db('s_order')->where(['order_id' => $order_id, 'service_type' => 0])->find();

        if (empty($order_info)) {
            return json_fail_return('暂无可操作订单');
        }

        if ($order_info['order_state'] == 4) {
            return json_fail_return('当前操作订单已完成，无需重复操作');
        }

        #判断主订单是否服务完成
        if ($order_info['service_state'] != 4) {
            return json_fail_return('服务人员未操作完成，您还不能点击完成');
        }

        //判断有没有追加的工时
        $order_append = db('s_order_append')->where(['order_id' => $order_id])->select();

        //如果有追加的工时单
        if (!empty($order_append)) {
            foreach ($order_append as $key => $value) {
                if ($value['status'] == 1) {
                    return json_fail_return('当前有待支付订单，请先支付');
                }
            }
        }

        //判断追加的设备是否确认收货了
        if ($order_info['app_order_id'] > 0) {
            $app_order_info = db('app_order')->where(['app_order_id' => $order_info['app_order_id']])->find();
            $order_ids = explode(",", $app_order_info['order_ids']);
            foreach ($order_ids as $item) {
                $order_infos = db('order')->where(['order_id' => $item])->find();
                if ($order_infos['order_state'] != 40) {
                    return json_fail_return('当前配件没有确认收货');
                }
            }
        }

        #追加订单完成
        $order_list = db('s_order')->where(['parent_id' => $order_id])->select();
        if ($order_list) {
            foreach ($order_list as $key => $value) {
                db('s_order')->where(['order_id' => $value['order_id']])->update(['order_state' => 4]);
            }
        }

        //订单完成，修改主单状态,结算服务人员金额
        db('s_order')->where(['order_id' => $order_id, 'member_id' => $member_id])->update(['order_state' => 4, 'finish_time' => time()]);

        $service_info = db('fuwu_personal')->where(['id' => $order_info['assign_mechanic_id']])->find();
        $service_money = $service_info['money'] + $order_info['assign_mechanic_total'];
        db('fuwu_personal')->where(['id' => $order_info['assign_mechanic_id']])->update(['money' => $service_money]);

        #服务单订单日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['log_msg'] = '客户确认服务完成';
        $data['log_time'] = time();
        $data['log_role'] = 'buyer';
        $data['log_user'] = $member_id;
        $data['log_orderstate'] = 4;

        model('order')->addSorderlog($data);
        return [];
    }


    /**
     * Notes:服务单用户三天内不点击自动服务完成
     * User: shen
     * Date: 2020/5/23
     * Time: 9:44
     * @param $order_id
     * @param $member_id
     * @return array|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function s_order_automatic_finish()
    {
        $today_time = mktime(0, 0, 0);

        #三天
        $begin_time = $today_time - 86400 * 3;
        $end_time = $today_time - 86400 * 2;
        //查询近三天前凌晨到第二天凌晨的服务订单
        $order_info = db('s_order')->where('mechanics_confirm_time', '<', $end_time)->where('mechanics_confirm_time', '>', $begin_time)->where(['service_state' => 4, 'order_state' => 7, 'parent_id' => 0])->select();
        if (!$order_info) {
            return json_fail_return('ok');
        }

        foreach ($order_info as $key => $value) {
            //判断有没有追加的工时
            $order_append = db('s_order_append')->where(['order_id' => $value['order_id']])->select();
            //如果有追加的工时单
            if (!empty($order_append)) {
                foreach ($order_append as $ke => $va) {
                    if ($va['status'] == 1) {
                        unset($order_info[$key]);
                        continue;
                    }
                }
            }

            //判断追加的设备是否确认收货了
            if ($value['app_order_id'] > 0) {
                $app_order_info = db('app_order')->where(['app_order_id' => $value['app_order_id']])->find();
                $order_ids = explode(",", $app_order_info['order_ids']);
                foreach ($order_ids as $item) {
                    $order_infos = db('order')->where(['order_id' => $item])->find();
                    if ($order_infos['order_state'] != 40) {
                        unset($order_info[$key]);
                        continue;
                    }
                }
            }
        }

        if ($order_info) {

            foreach ($order_info as $key => $value) {
                #追加订单完成
                $order_list = db('s_order')->where(['parent_id' => $value['order_id']])->select();
                if ($order_list) {
                    foreach ($order_list as $k => $val) {
                        db('s_order')->where(['order_id' => $val['order_id']])->update(['order_state' => 4]);
                    }
                }

                //订单完成，修改主单状态,结算服务人员金额
                db('s_order')->where(['order_id' => $value['order_id']])->update(['order_state' => 4, 'finish_time' => time()]);

                $service_info = db('fuwu_personal')->where(['id' => $value['assign_mechanic_id']])->find();
                $service_money = $service_info['money'] + $value['assign_mechanic_total'];
                db('fuwu_personal')->where(['id' => $value['assign_mechanic_id']])->update(['money' => $service_money]);
                #服务单订单日志
                $data = array();
                $data['order_id'] = $value['order_id'];
                $data['log_msg'] = '超出三天系统自动确认服务完成';
                $data['log_time'] = time();
                $data['log_role'] = 'buyer';
                $data['log_user'] = $value['member_id'];
                $data['log_orderstate'] = 4;
                model('order')->addSorderlog($data);
            }

            return json_fail_return('ok');

        } else {
            return json_fail_return('ok');
        }
    }


    /**
     * 服务单取消订单
     * @param array $order_info
     * @return array
     */
    public function changeSorderStateCancel($order_info, $role, $user = '', $app_order_id, $cantion_reason, $cancel_remark, $msg = '', $if_update_account = true, $if_quque = true, $if_pay = false)
    {
        $order_model = model('order');
        $order_id = $order_info['order_id'];

        //1、更改主服务单状态
        $update_s_order = [
            'order_state' => -1,
            'cantion_reason' => $cantion_reason,
            'cancel_remark' => $cancel_remark,
        ];
        db('s_order')->where(['order_id' => $order_id])->update($update_s_order);

        //2、取消主订单，也得把追加的订单也取消

        $s_order_append_info = db('s_order_append')->where(['order_id' => $order_id])->select();
        foreach ($s_order_append_info as $key => $value) {
            db('s_order_append')->where(['id' => $value['id']])->update(['status' => 3]);
        }
        //3、取消订单 返回相应积分
        // $member_info = db('member')->where(['member_id'=>$user])->find();
        // $count = $member_info['member_points'] + $res['use_integral'];
        // db('member')->where(['member_id'=>$user])->update(['member_points'=>$count]);

        //4、添加服务订单日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['log_msg'] = '取消了订单';
        $data['log_time'] = time();
        $data['log_role'] = $role;
        $data['log_user'] = $user;
        $data['log_orderstate'] = '-1';
        $data['log_make'] = 0;
        $order_model->addSorderlog($data);
        return [];
    }

    #生成商品单
    public function getGenerateSorder($order_id, $parts_ids)
    {

        $order_model = new \app\common\model\Order();
        $s_order_info = db('s_order')->where(['order_id' => $order_id])->find();

        #详情
        $goods_detail = db('s_order_detail')->where(['order_id' => $order_id])->select();

        $parts_lists = []; #需要生成商品单的的配件
        foreach ($goods_detail as $key => $value) {
            $parms = [
                'detail_order_id' => $value['id'],
                'is_bring_goods' => 0
            ];
            $part_list = db('s_order_parts')->where($parms)->field('id,good_id,num,sale_part_price,part_price')->select();
            if(!empty($part_list)){
                foreach ($part_list  as $k => $v) {
                    #找到商品
                    $goods_info = db('goods')->alias('g')
                        ->where(['g.goods_id' => $v['good_id']])
                        ->find();
                    $goods_info['parts_num'] = $v['num'];
                    $goods_info['sale_part_price'] = $v['sale_part_price'];
                    $goods_info['part_price'] = $v['part_price'];
                    $parts_lists[$k] = $goods_info;
                }
            }
        }
        if (!empty($parts_lists)) {

            $input_address_info = model('address')->getAddressInfo(array('address_id' => $s_order_info['address_id']));
            //获取收货人的信息
            list($reciver_info, $reciver_name) = $this->getReciverAddr($input_address_info);

            #根据店铺id不同分类
            $store_cart_list = $this->_getStoreCartList($parts_lists);

            //运营商
            $yys_id = get_service_parent_store_id($s_order_info['member_id']);
            $yys_info = db('store')->where('store_id', $yys_id)->find();

            #将不同店铺的数据分开
            foreach ($store_cart_list as $store_id => $goods_list) {
                #获取店铺信息
                $store_info = db('store')->where(['store_id' => $store_id])->find();

                #生成商品订单
                $order_data = [
                    'order_sn' => $s_order_info['order_sn'],
                    'pay_sn' => $s_order_info['pay_sn'],
                    'buyer_id' => $s_order_info['member_id'],
                    'buyer_name' => $s_order_info['member_name'],
                    'store_id' => $store_id,
                    'store_name' => $store_info['store_name'],
                    'add_time' => time(),
                    'payment_code' => $s_order_info['payment_code'],
                    'payment_time' => $s_order_info['payment_time'],
                    'goods_amount' => $s_order_info['pay_amount'],
                    'order_amount' => $s_order_info['order_amount'],
                    'order_state' => 20,
                    'order_type' => 2,
                    'yys_id' => $yys_id,
                    'yys_name' => $yys_info['store_name'],
                    'orderservice_id' => $s_order_info['order_id']
                ];

                $order_mall_id = db('order')->insertGetId($order_data);

                $order_info['order_id'] = $order_mall_id;
                $order_list[$order_mall_id] = $order_info;


                // 将主单id放入服务单里面
                db('s_order')->where(['order_id' => $order_id])->update(['order_mall_id' => $order_mall_id, 'is_generate' => 1]);

                //4、生成订单扩展表信息  （用于发货）
                $order_common['order_id'] = $order_mall_id;
                $order_common['store_id'] = $store_id;
                $order_common['reciver_info'] = $reciver_info;
                $order_common['reciver_name'] = $reciver_name;
                $order_model->addOrdercommon($order_common);

                #生成ordergoods
                foreach ($goods_list as $key => $value) {
                    $goods_info = db('goods')->where(['goods_id' => $value['goods_id']])->find();

                    #商品扩展表
                    $ordergoods['order_id'] = $order_mall_id;
                    $ordergoods['goods_id'] = $value['goods_id'];
                    $ordergoods['goods_name'] = $value['goods_name'];
                    $ordergoods['goods_price'] = $goods_info['goods_price'];
                    $ordergoods['goods_num'] = $value['parts_num'];
                    $ordergoods['goods_image'] = $goods_info['goods_image'];
                    $ordergoods['store_id'] = $store_id;
                    $ordergoods['buyer_id'] = $s_order_info['member_id'];
                    $ordergoods['goods_pay_price'] = $value['sale_part_price'];
                    $ordergoods['goods_original_price'] = $goods_info['goods_price'];  #供应商给平台的价格（展示在供应商）
                    $ordergoods_id = db('ordergoods')->insertGetId($ordergoods);
                }
            }

            //大订单表
            $order_ids_array = array_keys($order_list);
            $order_ids = implode(',', $order_ids_array);
            $total['order_ids'] = $order_ids;

            $order_goods_info = db('ordergoods')->where('order_id', 'in', $order_ids)->select();
            if (!empty($order_goods_info)) {
                $total['goods_ids'] = implode(',', array_column($order_goods_info, 'goods_id'));
                $total['ordergoods_ids'] = implode(',', array_column($order_goods_info, 'rec_id'));
            }
            $total['price'] = $s_order_info['order_amount'];
            $total['order_status'] = 1;
            $total['app_order_type'] = 3;
            $total['order_sn'] = time() . '123';
            $total['pay_sn'] = $s_order_info['pay_sn'];
            $total['create_time'] = time();
            $total['user_id'] = $s_order_info['member_id'];
            $total['user_name'] = $input_address_info['address_realname'];
            $total['member_name'] = $s_order_info['member_name'];

            $total['phone'] = $s_order_info['appoint_phone'];
            $total['user_address'] = $s_order_info['appoint_address'] . $s_order_info['appoint_detail_address'];

            $total['app_order_service_id'] = $order_id;

            //下单使用了多少积分
            $total['use_integral'] = $s_order_info['order_integral'];

            //下单使用优惠劵优惠了多少钱
            $total['voucher_price'] = $s_order_info['voucher_price'];

            db('app_order')->data($total)->insert();
            $Id = db('app_order')->getLastInsID();
            $aa = db('order')->data(['apporder_id' => $Id])->where('order_id', 'in', $order_mall_id)->update();
            db('s_order')->where(['order_id' => $order_id])->update(['app_order_id' => $Id]);
        }
    }

    /**
     * 取得收货人地址信息
     * @param array $address_info
     * @return array
     */
    public function getReciverAddr($address_info = array())
    {
        if (intval($address_info['dlyp_id'])) {
            $reciver_info['phone'] = trim($address_info['dlyp_mobile'] . ($address_info['dlyp_telephony'] ? ',' . $address_info['dlyp_telephony'] : null), ',');
            $reciver_info['tel_phone'] = $address_info['dlyp_telephony'];
            $reciver_info['mob_phone'] = $address_info['dlyp_mobile'];
            $reciver_info['address'] = $address_info['dlyp_area_info'] . ' ' . $address_info['dlyp_address'];
            $reciver_info['area'] = $address_info['dlyp_area_info'];
            $reciver_info['street'] = $address_info['dlyp_address'];
            $reciver_info['dlyp'] = 1;
            $reciver_info = serialize($reciver_info);
            $reciver_name = $address_info['dlyp_addressname'];
        } else {
            $reciver_info['phone'] = trim($address_info['address_mob_phone'] . ($address_info['address_tel_phone'] ? ',' . $address_info['address_tel_phone'] : null), ',');
            $reciver_info['mob_phone'] = $address_info['address_mob_phone'];
            $reciver_info['tel_phone'] = $address_info['address_tel_phone'];
            $reciver_info['address'] = $address_info['area_info'] . ' ' . $address_info['address_detail'];
            $reciver_info['area'] = $address_info['area_info'];
            $reciver_info['street'] = $address_info['address_detail'];
            $reciver_info = serialize($reciver_info);
            $reciver_name = $address_info['address_realname'];
        }
        return array($reciver_info, $reciver_name);
    }


    /**
     * 将下单商品列表转换为以店铺ID为下标的数组
     *
     * @param array $cart_list
     * @return array
     */
    private function _getStoreCartList($projectgoods_list)
    {
        if (empty($projectgoods_list) || !is_array($projectgoods_list))
            return $projectgoods_list;
        $new_array = array();
        foreach ($projectgoods_list as $cart) {
            $new_array[$cart['store_id']][] = $cart;
        }
        return $new_array;
    }


    private function makeOrderSn()
    {
        $date = date('Ymd');
        $num = $date . '0000' . substr(time(), 3, 7) . rand(1000, 999);

        return $num;
    }
}
